package com.cloud.async.util;

import com.cloud.async.business.core.AsyncTaskLifecycle;
import com.cloud.async.business.core.BaseAsyncResultHandler;
import com.cloud.async.error.ErrorHandler;
import com.cloud.async.error.impl.DefaultErrorHandler;
import com.cloud.async.monitor.ResultHandlerMonitor;
import com.cloud.async.monitor.impl.DefaultResultHandlerMonitor;
import com.cloud.async.result.core.handler.StandardAsyncResultHandler;
import com.cloud.async.retry.DefaultRetryPolicy;
import com.cloud.async.retry.RetryPolicy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author chengrui
 * @title: ApplicationContext
 * @projectName webCloudAsync
 * @description: create AsyncResultHandler
 * @date 2025/07/27 15:32
 */
public class ClassAsyncResultUtils {

    private static final String DEFAULT_ASYNC_RESULT = "com.cloud.async.result.core.handler.StandardAsyncResultHandler";

    public static BaseAsyncResultHandler createAsyncResultHandler(Long milliSecond, AsyncTaskLifecycle asyncBusiness,
            Class<?> resultHandlerClass,  Class<? extends ErrorHandler> errorHandlerClass , Class<? extends ResultHandlerMonitor> monitorClass) {
        try {

            if (resultHandlerClass == null) {
                resultHandlerClass = StandardAsyncResultHandler.class;
            }
            if (errorHandlerClass == null) {
                errorHandlerClass = DefaultErrorHandler.class;
            }
            if (monitorClass == null) {
                monitorClass = DefaultResultHandlerMonitor.class;
            }


            // 1. 反射创建 ErrorHandler 实例
            ErrorHandler errorHandler = errorHandlerClass.getDeclaredConstructor().newInstance();

            // 2. 反射创建 ResultHandlerMonitor 实例
            ResultHandlerMonitor monitor = monitorClass.getDeclaredConstructor().newInstance();


            // 1. 获取目标类的构造函数
            Constructor<?> constructor = resultHandlerClass.getConstructor(
                    Long.class,
                    AsyncTaskLifecycle.class,
                    ErrorHandler.class,
                    ResultHandlerMonitor.class
            );

            // 2. 通过反射调用构造函数
            return (BaseAsyncResultHandler) constructor.newInstance(
                    milliSecond,
                    asyncBusiness,
                    errorHandler,
                    monitor
            );
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(
                    "No matching constructor found for " + resultHandlerClass.getName(), e
            );
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new IllegalStateException(
                    "Failed to instantiate " + resultHandlerClass.getName(), e
            );
        }
    }


    public static BaseAsyncResultHandler createAsyncResultHandlerExp(Long milliSecond, AsyncTaskLifecycle asyncBusiness,
                                                                  Class<?> resultHandlerClass,  ErrorHandler errorHandler ,
                                                                  ResultHandlerMonitor monitor) {
        try {
            if (resultHandlerClass == null) {
                resultHandlerClass = StandardAsyncResultHandler.class;
            }
            // 1. 获取目标类的构造函数
            Constructor<?> constructor = resultHandlerClass.getConstructor(
                    Long.class,
                    AsyncTaskLifecycle.class,
                    ErrorHandler.class,
                    ResultHandlerMonitor.class
            );

            // 2. 通过反射调用构造函数
            return (BaseAsyncResultHandler) constructor.newInstance(
                    milliSecond,
                    asyncBusiness,
                    errorHandler,
                    monitor
            );
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(
                    "No matching constructor found for " + resultHandlerClass.getName(), e
            );
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new IllegalStateException(
                    "Failed to instantiate " + resultHandlerClass.getName(), e
            );
        }
    }


    /**
     * 创建重试策略
     * @param retryPolicyCls
     * @param retryPolicy
     * @return
     */
    public static RetryPolicy createRetryPolicy(Class<? extends RetryPolicy> retryPolicyCls, RetryPolicy retryPolicy) {
        if (retryPolicyCls != null) {
            try {
                return retryPolicyCls.getDeclaredConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException |
                    InvocationTargetException e) {
                throw new IllegalStateException("Failed to instantiate " + retryPolicyCls.getName(), e);
            }
        }
        if (retryPolicy != null) {
            return retryPolicy;
        }
        try {
            retryPolicyCls = DefaultRetryPolicy.class;
            // 使用反射创建无参的 DefaultRetryPolicy 对象
            return retryPolicyCls.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException |
                InvocationTargetException e) {
            throw new IllegalStateException("Failed to instantiate default " + retryPolicyCls.getName(), e);
        }
    }



}
